package Process;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * This process waits for any type of
 * user input from the console.
 * 
 * @author Stephen Amos, Zach Turk, Dickson Kwong
 */
public class UserInput extends Process
{
	boolean gui_set = false;
	private char my_char;
	
	public UserInput(int the_id, SysCall[] the_requests, int the_counter) 
	{
		super(the_id, the_requests, the_counter);
		
		for (int i = 0; i < Math.floor(requests.length/2); i++)
		{
			requests[(int) Math.floor(Math.random() * requests.length)] = SysCall.KEYBOARD_IO;
		}
	}

	/**
	 * Runs this process.
	 */
	public void run()
	{
		gui_set = true;
	    JFrame frame = new JFrame("Keyboard process running.  Press any key...");
	    Container contentPane = frame.getContentPane();
	    final JTextField text = new JTextField();
	    KeyListener listener = new KeyListener() 
	    {
	      public void keyPressed(KeyEvent e) 
	      {
	    	  //Do nothing
	      }

	      public void keyReleased(KeyEvent e) 
	      {
	    	  //Do nothing
	      }

	      public void keyTyped(KeyEvent e) 
	      {
	    	  //System.out.println("Key input detected. Key typed: " + e.getKeyChar());
	    	  my_char = e.getKeyChar();
	    	  setChanged();
	    	  notifyObservers();
	    	  text.setText("Input: ");
	      }

	    };
	    text.setText("Input: ");
	    text.addKeyListener(listener);
	    contentPane.add(text, BorderLayout.NORTH);
	    frame.setResizable(false);
	    Font my_font = new Font("Arial", Font.PLAIN, 24);
	    text.setFont(my_font);
	    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	    frame.setAlwaysOnTop(true);
	    frame.pack();
	    frame.setVisible(true);
	}
	
	/**
	 * Returns the character associated with this user input process.
	 * 
	 * @return The character to be returned.
	 */
	public char getChar()
	{
		return my_char;
	}
	
	
	/**
	 * Returns the process request and updates the program counter
	 * of this process to the next request.
	 */
	public SysCall next()
	{
		if (!gui_set)
		{
			run();
		}
		return super.next();
	}
}
